#define _CRT_SECURE_NO_DEPRECATE 
#include "engineFactory.h"


engineFactory::engineFactory(HINSTANCE hInst)
{
	this->hInst = hInst;
	this->pEngine = NULL;

}

engineFactory::~engineFactory()
{
	if(this->pEngine)
		destroyInterface();
}

HRESULT engineFactory::initInterface(TCHAR *szIniFile)
{
	TCHAR currentPath[MAX_PATH];
	ZeroMemory(&currentPath, sizeof(MAX_PATH));
	GetCurrentDirectory(MAX_PATH, currentPath);
	strcat(currentPath, "\\");
	strcat(currentPath, szIniFile);

	DWORD dwRetVal = 0;
	TCHAR szType[MAX_PATH];
	DWORD dwSizeVal = MAX_PATH;
	dwRetVal = GetPrivateProfileString("Video",    // section name
									  "Renderer",       // key name
									  "Direct3D", // default string
									  szType,      // destination buffer
									  dwSizeVal,       // size of destination buffer
									  currentPath);   // initialization file name


	if(strcmp(szType, "OpenGL") == 0)
	{
		hDLL = LoadLibraryEx("immkp97OGLengine.dll",NULL,0);
		if(!hDLL)
		{
			MessageBox(NULL,
					   "Error loading up immkp97OGLengine.dll",
					   "Fatal Error",
					   MB_OK | MB_ICONERROR);

			return E_FAIL;
		}

//Done OK		MessageBox(NULL, "Loaded up OpenGL renderer", "Info", MB_OK | MB_ICONINFORMATION);

	}
	else
	{
		hDLL = LoadLibraryEx("immkp97D3Dengine.dll",NULL,0);
		if(!hDLL)
		{
			MessageBox(NULL,
					   "Error loading up immkp97D3Dengine.dll",
					   "Fatal Error",
					   MB_OK | MB_ICONERROR);

			return E_FAIL;
		}

//Done OK		MessageBox(NULL, "Loaded up Direct3D renderer", "Info", MB_OK | MB_ICONINFORMATION);


	}

	CREATEENGINEINTERFACE CreateInterface = 0;
	HRESULT hr;

	CreateInterface = (CREATEENGINEINTERFACE)GetProcAddress(hDLL,
				 "createEngineInterface");
	if(NULL==CreateInterface) {
		MessageBox(NULL,
				   "Error using GetProcAddress for createEngineInterface function",
				   "FATAL Error", MB_OK | MB_ICONERROR);
		pEngine = NULL;
		return E_FAIL;
	}

	hr = CreateInterface(&pEngine);
	if(FAILED(hr)){
		MessageBox(NULL,
				   "Error using our createInterface function",
				   "FATAL Error", MB_OK | MB_ICONERROR);
		pEngine = NULL;
		return E_FAIL;
	}

	return S_OK;
}

void engineFactory::destroyInterface()
{
	DESTROYENGINEINTERFACE DestroyInterface = 0;
	HRESULT hr;

	DestroyInterface = (DESTROYENGINEINTERFACE)GetProcAddress(hDLL,
				"destroyEngineInterface");
	hr = DestroyInterface(&pEngine);
	if(FAILED(hr)){
		MessageBox(NULL,
				   "Error using our destroyInterface function",
				   "ImmKpGraphics Error", MB_OK);

		pEngine = NULL;
	}
}